import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import formInfo from '@ohos.app.form.formInfo';
import { KeyboardAvoidMode } from '@kit.ArkUI';

const SPLASH_PAGE = 'pages/SplashPage'
const STATUS_BAR_COLOR: string = '#000000';
const STATUS_BAR_CONTENT_COLOR: string = '#ffffff';

const ROUTER_TYPE_MAIN: string = 'Main'
const ROUTER_TYPE_TO_SPECIFY: string = 'ToSpecify'

let currentWindowStage: window.WindowStage = null;

export default class EntryAbility extends UIAbility {
  // 初始化LocalStorage
  storage: LocalStorage = new LocalStorage({
    'cardId': '',
    'routerType': '',
    'routerUrl': ''
  })

  // 如果UIAbility第一次启动，在收到Router事件后会触发onCreate生命周期回调
  onCreate(want, launchParam) {

    // 获取router事件中传递的targetPage参数
    console.info("[EntryAbility] onCreate want=" + JSON.stringify(want) +
      ',launchParam=' + JSON.stringify(launchParam));

    // 处理卡片跳转参数
    this.handleCardParams(want)
  }

  // 如果UIAbility已在后台运行，在收到Router事件后会触发onNewWant生命周期回调
  onNewWant(want, launchParam) {
    console.info("[EntryAbility] onNewWant want=" + JSON.stringify(want) +
      ',launchParam=' + JSON.stringify(launchParam));

    // 处理卡片跳转参数
    this.handleCardParams(want)
  }

  /**
   * 处理卡片跳转参数
   * @param want want参数
   */
  handleCardParams(want) {

    // 接收到了卡片传递的消息
    if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {

      let params = JSON.parse(want.parameters.params);
      let cardId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
      let cardName = want.parameters[formInfo.FormParam.NAME_KEY];

      console.info("[EntryAbility] handleCardParams card action params=" +
      JSON.stringify(params) + ',cardId=' + cardId + ',cardName=' + cardName);

      if (params.routerUrl !== undefined) { // router跳转

        let routerType = params.routerType;
        let routerUrl = params.routerUrl;

        // 保存到LocalStorage中
        this.storage.setOrCreate('cardId', cardId)
        this.storage.setOrCreate('routerType', routerType)
        this.storage.setOrCreate('routerUrl', routerUrl)

        // 重新调用windowStage加载
        if (currentWindowStage != null) {
          console.info("[EntryAbility] onNewWant WindowStage reloadContent")
          this.onWindowStageCreate(currentWindowStage);
        }
      }
    }
  }


  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability

    let routerType = this.storage.get('routerType');
    let routerUrl = this.storage.get('routerUrl');

    console.info("[EntryAbility] onWindowStageCreate routerType=" +
      routerType + ",routerUrl=" + routerUrl);

    let path;
    // 根据传递的targetPage不同，选择拉起不同的页面
    switch (routerType) {
      case ROUTER_TYPE_MAIN:
        path = routerUrl;
        break;
      case ROUTER_TYPE_TO_SPECIFY:
        path = routerUrl
        break;
      default:
        path = SPLASH_PAGE;
    }

    currentWindowStage = windowStage;

    windowStage.loadContent(path, this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
      // 设置全窗颜色和应用元素颜色一致
      // windowStage.getMainWindowSync().setWindowBackgroundColor('#FFEDEDED');
      // let keyboardAvoidMode = windowStage.getMainWindowSync().getUIContext().getKeyboardAvoidMode();
      // 设置虚拟键盘抬起时压缩页面大小为减去键盘的高度
      windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
    });

    // 监听window状态
    try {
      windowStage.on('windowStageEvent', (stageEventType) => {
        switch (stageEventType) {
          case window.WindowStageEventType.SHOWN:
            console.log("[EntryAbility] onWindowStageCreate shown");
            //this.immersiveWindow(windowStage, true)
            break;
          case window.WindowStageEventType.ACTIVE:
            console.log("[EntryAbility] onWindowStageCreate active");
            break;
          case window.WindowStageEventType.INACTIVE:
            console.log("[EntryAbility] onWindowStageCreate inActive");
            break;
          case window.WindowStageEventType.HIDDEN:
            console.log("[EntryAbility] onWindowStageCreate hidden");
            break;
          default:
            break;
        }
      })
    } catch (exception) {
      console.error('Failed to enable the listener for window stage event changes. Cause:' +
      JSON.stringify(exception));
    }
  }

  onForeground() {
    // Ability has brought to foreground
    console.log("[EntryAbility] onForeground ------->");
  }

  onBackground() {
    // Ability has back to background
    console.log("[EntryAbility] onForeground ------->");
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    console.log("[EntryAbility] onForeground ------->");
  }

  onDestroy() {
    console.log("[EntryAbility] onForeground ------->");
  }

  immersiveWindow(windowStage: window.WindowStage, isLayoutFullScreen: boolean) {

    let windowClass: window.Window | null = null;
    windowStage.getMainWindow((err, data: window.Window) => {
      if (err.code) {
        console.error(`Failed to obtain the main window. Cause: ${JSON.stringify(err)}`);
        return;
      }

      windowClass = data;
      console.info(`Succeeded in obtaining the main window. Data:  ${JSON.stringify(data)}`);

      let systemBarProperties: window.SystemBarProperties = {
        statusBarColor: STATUS_BAR_COLOR,
        navigationBarColor: STATUS_BAR_COLOR,
        //以下两个属性从API Version8开始支持
        statusBarContentColor: STATUS_BAR_CONTENT_COLOR,
        navigationBarContentColor: STATUS_BAR_CONTENT_COLOR
      };

      windowClass.setWindowSystemBarProperties(systemBarProperties, (err) => {
        if (err.code) {
          // 801 该设备不支持此API
          console.error(`Failed to set the system bar properties. Cause: ${JSON.stringify(err)}`)
          return;
        }
        console.info('Succeeded in setting the system bar properties.')
      });

      windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, (err) => {
        if (err.code) {
          console.error(`Failed to set the window layout to full-screen mode. Cause: ${JSON.stringify(err)}`);
          return;
        }
        console.info('Succeeded in setting the window layout to full-screen mode.');
      });
    });
  }
}
